<?php
namespace app\admin\controller;

use think\Controller;
use think\Request;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\ErrorCorrectionLevel;


/**
 * 
 */
class Wxpay extends Common
{
	//扫码支付
    public function native(){
        //获取微信配置
        $wxConf = config('wechat');
        //实例化easyWeChat
        $wxApp = new Application($wxConf);
        //支付订单参数
        $attributes = [
            'trade_type'       => 'NATIVE', // JSAPI，NATIVE，APP...
            'body'             => '这里是body',
            'detail'           => '这里是detail，可选',
            'out_trade_no'     => time(),
            'total_fee'        => 1, // 单位：分// 支付结果通知网址，如果不设置则会使用配置里的默认地址
        ];
        //初始化订单
        $order = new Order($attributes);
        //实例化支付
        $payment = $wxApp->payment;
        //预支付
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $codeUrl = $result->code_url;
            //生成二维码
            if(substr($codeUrl, 0, 6) == "weixin"){
			    createQrcodeOriginal($codeUrl);
            }else{
                header('HTTP/1.1 404 Not Found');
            }


            $order = new QrCode($codeUrl);
            $order->setSize(300)
                ->setWriterByName('png')
                ->setMargin(10)
                ->setEncoding('utf-8')
                ->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH)
                ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0])
                ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255])
//                ->setLogoPath(ROOT_PATH . 'template/common/images/wxpay.png')
//                ->setLogoWidth(65)
                ->setValidateResult(false);
            $order->writeFile(ROOT_PATH . "uploads/qrcode.png");
            $imgData= imgToBase64(ROOT_PATH . "uploads/qrcode.png");
            return json(['errcode'=>0,'msg'=>'发起支付成功','imgData'=>$imgData]);
        }else{
            return json(['errcode'=>1,'msg'=>'发起支付失败，稍后再试吧']);
        }
    }

	//微信jsapi支付
	public function jsapi(){
		if (!Request::instance()->isAJAX()) return view ('Error/index');
		$money = 1;
		//创建支付订单
		if($money) {
			// $wxConf = [
			// 	// 前面的appid什么的也得保留哦
			// 	'app_id' => 'xxxx',
			// 	// ...
			// 	// payment
			// 	'payment' => [
			// 	'merchant_id' => 'your-mch-id',
			// 	'key' => 'key-for-signature',
			// 	'cert_path' => getcwd() . "\\Cert\\wechat\\apiclient_cert.pem", // XXX: 绝对路径！！！！
			// 	'key_path' => getcwd() . "\\Cert\\wechat\\apiclient_key.pem", // XXX: 绝对路径！！！！
			// 	'notify_url' => 'http://www.xxx.com/wxnotify/notify.html', // 你也可以在下单时单独设置来想覆盖它
			// 	],
			// ];
			$wxConf = config('wechat');
			//实例化easyWeChat

			$wxApp = new Application($wxConf);
			$payment = $wxApp->payment;

			$attributes = [
				'trade_type' => 'JSAPI', // JSAPI，NATIVE，APP...
				'body' => '充值测试-',
				'detail' => '测试',
				'out_trade_no' => time(),
				'total_fee' => $money, // 单位：分
				// 'notify_url' => '', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
				'openid' => 'oBrSLw1y5hxm7Mrdrvh0adr1oXtU', // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
			];		
			$order = new Order($attributes);
			$result = $payment->prepare($order);
			if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') 
			{
				$prepayId = $result->prepay_id;
				$json = $payment->configForPayment($prepayId);
				return json(['error'=>1001,'data' => $json]);
			}else{
				return json(['error'=>1000,'msg' => '网络繁忙，稍后重试']);
			}
		}else{
			return json(['error'=>1000,'msg' => '网络繁忙，稍后重试']);
		}
	}
}
